/*
 * @Author: xiaozhuang-c-language 3535851673@qq.com
 * @Date: 2025-10-25 10:52:38
 * @LastEditors: xiaozhuang-c-language 3535851673@qq.com
 * @LastEditTime: 2025-10-25 11:06:38
 * @FilePath: /zhuang/grpc-cpp-hello/server/server.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<grpcpp/grpcpp.h>
#include "../generated/hello.pb.h"
#include "../generated/hello.grpc.pb.h"

#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server_builder.h>
#include <iostream>
#include <memory>
#include <string>

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using hello::Greeter;
using hello::HelloReply;
using hello::HelloRequest;

//继承由protoc生成的服务基类,覆盖rpc方法
class GreeterServiceImpl final : public Greeter::Service
{
   public:
     Status SayHello(ServerContext* context, const HelloRequest* request,HelloReply* response)
     {
           std::string msg = "Hello " + request->name() + "! [from gRPC Server]";
           response->set_message(msg);
           return Status::OK;        
     }
};

//启动服务器注册rpc服务
void RunServer(const std::string& address)
{
    GreeterServiceImpl service;
    ServerBuilder builder;
    //绑定监听地址，使用明文通道(实际生产建议用TLS)
    //InsecureServerCredentials()告诉grpc服务器使用明文传输协议，不对数据进行加密，可以快速搭建服务，不需要配置SSL、TLS证书
    builder.AddListeningPort(address,grpc::InsecureServerCredentials());
    //注册服务实现
    builder.RegisterService(&service);

    std::unique_ptr<Server> server(builder.BuildAndStart());
    //该函数:1.收集buidler设置的配置项目
    //2.创建Server实例
    //3.为每个监听端口建立监听器
    //4.注册用户定义的服务
    //5.启动服务器线程池与监听器
    std::cout << "RPC Server Listening on " << address << std::endl;
    server->Wait();
}

int main() {
  RunServer("0.0.0.0:50051");
  return 0;
}